/**
 * create by young (young2f@outlook.com) on 2020/8/21
 */


'use strict';
import React from 'react';
import {connect} from 'dva/index';
import {Button, Form, Popconfirm, Table, Tabs, Tag} from 'antd';
import {ModalView} from 'antd-extra';
import ModalSelectMeter from '../modals/ModalSelectMeter';
import DirTree from '../../components/DirTree';
import styles from '../index.less';
import ViewTitle from '../../components/ViewTitle';
import notify from '../../components/NotificationExtra';
import TreeBase from '../../components/Base/TreeBase';
import ProductionElement from '../../components/ProductionElement';
import ModalSelectUser from '../modals/ModalSelectUser';

const {TabPane} = Tabs;

const table = 'organization';

const title = '生产组织';
@Form.create()
@connect(({global, treeNode, organization, user, device}) => ({...organization, ...global, ...device, ...treeNode, ...user}))
export default class Index extends TreeBase {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    this.state.treeNode && this.onLoadData().then(res => {
      this.setState(res);
    });
  }

  async onLoadData() {
    const {treeId} = this.state.treeNode;
    const res = await this.props.dispatch({
      type: 'organization/findBindMeters',
      payload: {organizationCode: treeId},
    });

    const bondedMeters = res && res.result ? res.result : [];

    return {bondedMeters};
  };

  onTreeDelete = (_id, result) => {
    const loginInfo = wStore.getStore('loginInfo');
    const {tenantCode} = loginInfo;
    const where = {organizationCode: _id, tenantCode};
    if (result.status === 'ok') {
      this.props.dispatch({
        type: 'device/updateDevice',
        payload: {table: 'device', where, data: {organizationCode: ''}},
      });
    }
  };

  bindMeter = () => {
    const {treeNode, bondedMeters} = this.state;
    const {dispatch} = this.props;

    const {name, path, treeId} = treeNode;
    console.log('bondedDevices11', bondedMeters)
    ModalView.open(ModalSelectMeter,
      {title: '选择计量仪表', width: '960px', height: '80%', noStore: true}, {
        dispatch,
        selectedDevices: bondedMeters,
        result: (devices => {
          console.log('bind device', devices);
          const payload = {organizationCode: treeId, organizationName: path + name, devices};
          dispatch({
            type: 'organization/bindMeter',
            payload: payload,
          })
            .then(res => {
              this.requestReturn(res);
              this.componentDidMount();
            });
        }),
      });


  };
  // createDevice = () => {
  //   const w = window.open('about:blank');
  //   w.location.href = '#/deviceCfg/thingModels';
  // };

  unbindDevice = record => {
    record.points = undefined;
    const {treeNode} = this.state;
    const {dispatch} = this.props;

    const {treeId} = treeNode;
    record.organizationCode = treeId;
    dispatch({
      type: 'organization/unbindMeter',
      payload: record,
    })
      .then(res => {
        this.requestReturn(res);
        this.componentDidMount();
      });
  };

  meterCols = () => {
    const columns = [
      {
        title: '仪表名称', dataIndex: 'meterName', key: 'meterName',

      },
      // { title: '设备类型', dataIndex: 'deviceType', key: 'deviceType' },
      {title: '仪表ID', dataIndex: 'meterId', key: 'meterId'},
      {title: '仪表类型', dataIndex: 'meterType', key: 'meterType'},
      {
        title: '是否启用', dataIndex: 'isEnabled', key: 'isEnabled', render: value => {
          return value ? <Tag color="green">启用</Tag> : <Tag color="red">禁用</Tag>;
        }
      },
      {
        title: '状态', dataIndex: 'isOnline', key: 'isOnline', render: (value) => {
          return value ? <Tag color="green">在线</Tag> : <Tag color="red">离线</Tag>;
        }
      },
      {
        title: '操作', dataIndex: 'action',
        width: 150, render: (text, record) => {
          return (
            <span>
              <Popconfirm title="确认解绑此设备？" onConfirm={() => {
                this.unbindDevice(record);
              }} okText="确认" cancelText="取消">
                <a>解绑</a>
              </Popconfirm>
              {/*<Button type={'link'}>详情</Button>*/}
              </span>
          );
        },
      },
    ];
    return columns;
  };

  meterTab = () => {
    const {treeNode, bondedMeters = []} = this.state;

    let subTitle = this.getTreeSubTitle(treeNode);
    return (
      <div className='antTable'>
        <ViewTitle
          title={'计量仪表列表'}
          level={2}
          subTitle={subTitle}
          actions={
            <div
              style={{marginBottom: '6px'}}
            >
              {/*<Button style={{zIndex: 99}} onClick={this.createDevice.bind(this)}>创建设备</Button>*/}
              <Button type="primary" style={{marginLeft: '12px', zIndex: 99}}
                      onClick={this.bindMeter.bind(this)}>绑定计量仪表</Button>
            </div>
          }
        ></ViewTitle>
        {<Table
          bordered={true}
          columns={this.meterCols()}
          dataSource={bondedMeters}
        ></Table>}
      </div>
    );
  };


  dataPage = () => {
    const {treeNode} = this.state;
    if (!treeNode) return;

    return (
      <div style={{marginTop: 0}}>
        <Tabs defaultActiveKey="1">
          <TabPane tab="计量仪表" key="1">
            {this.meterTab()}
          </TabPane>
          {/*<TabPane tab="设备" key="2">*/}
          {/*  {this.employee()}*/}
          {/*</TabPane>*/}
        </Tabs>
      </div>
    );
  };
  onTreeNodeSelected = (node) => {
    if (!node) return;
    this.state.treeNode = node;
    this.componentDidMount();
  };

  render() {
    const {expandedKeys, dispatch} = this.props;
    return (
      <Form className={styles.content}>
        <DirTree
          table={table}
          dispatch={dispatch}
          onTreeDelete={this.onTreeDelete}
          onTreeNodeSelected={this.onTreeNodeSelected}
          expandedKeys={expandedKeys}
          defaultExpandAll={true}
          title={title}

        > {this.dataPage()}</DirTree>
      </Form>
    );
  }
}
